'use strict';

const Controller = require('egg').Controller;
//jwt
const jwt = require('jsonwebtoken')

class HomeController extends Controller {
    //登录
    async Login() {
        const { ctx, app } = this;
        const { username, password } = ctx.request.body
        const data = await app.mysql.get('login', { username, password })
        // const data = await app.mysql.query(`select * from login where username = "${username}" and password = "${password}"`)

        // const datas = data.map(item => {
        //     return {
        //         id: item.id,
        //         username: item.username,
        //         img: item.img,
        //         auth: item.auth,
        //     }
        // })

        // //jwt加密 设置失效时间   1m 一分钟
        // let token = jwt.sign({ ...data }, '1901A', { expiresIn: '1m' })

        if (data) {
            //jwt加密 设置失效时间   1m 一分钟
            let token = jwt.sign({ ...data }, '1901A', { expiresIn: '20m' })

            ctx.body = {
                code: 200,
                // datas,
                data,
                token,
            }
        } else {
            ctx.body = {
                code: 400,
            }
        }
    }

    //注册
    async Regsiter() {
        const { ctx, app } = this;
        const img = 'https://img1.baidu.com/it/u=1897719880,2867606276&fm=26&fmt=auto'
        const { username, password } = ctx.request.body
        const auth='管理员'
        // const data = await app.mysql.get("login", { username })
        // if (!data && username, password !== '') {
        //     await app.mysql.insert("login", { username, password,img})
        //     ctx.body = {
        //         code: 200,
        //     }
        // } else {
        //     ctx.body = {
        //         code: 400,
        //     }
        // }
        if (await app.mysql.get('login', { username })) {
            ctx.body = {
                code: 400
            }
        } else {
            await app.mysql.insert('login', { username, password, img ,auth})
            ctx.body = {
                code: 200
            }
        }

        // if (await app.mysql.insert('login', { username, password, img })) {
        //     ctx.body = {
        //         code: 200
        //     }
        // } else {
        //     await app.mysql.get('login', { username })
        //     ctx.body = {
        //         code: 400
        //     }
        // }

    }

}

module.exports = HomeController;